 
package org.unisannio.sc;

import org.unisannio.remote.GenericRemote;
import org.unisannio.remote.RemoteContentProvider;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.Toast;


public class QueryContactsTask extends AsyncTask<GenericRemote, Integer, Cursor> {

	private Activity activity;
	private ProgressDialog dialog;
	private String display_name;
	public QueryContactsTask(Activity activity,String display_name) {
		this.activity = activity;
		this.display_name=(display_name=="") ? "%" : display_name;
	}

	@Override
	protected void onPreExecute() {
		dialog = ProgressDialog.show(activity, "",
				"Querying. Please wait...", true);
	}

	@Override
	protected Cursor doInBackground(GenericRemote... remote) {
		Uri uri = Data.CONTENT_URI;
//		
		String[] params=new String[3];
		params[0]="%"+display_name+"%";
		params[1]=Phone.CONTENT_ITEM_TYPE;
		params[2]="shared";
		String where=Data.DISPLAY_NAME+ " LIKE ? " + "AND " +Data.MIMETYPE + "= ? " +"AND "+ Phone.NUMBER + " IS NOT NULL" + " AND " +Phone.LABEL + "= ?";		
		Cursor cursor = ((RemoteContentProvider) remote[0]).query(uri, null,
				where, params, null);
		return cursor;
	}

	@Override
	protected void onPostExecute(Cursor cursor) {
		dialog.dismiss();
		
		if (cursor == null) {
			((ShareContactsApp)activity.getApplication()).setResultCursor(cursor);
			Toast toast = Toast
					.makeText(
							activity,
							"Nessun risultato disponbile",
							Toast.LENGTH_LONG);
			toast.show();
		} else {



			((ShareContactsApp)activity.getApplication()).setResultCursor(cursor);
			MainActivity mainActivity=(MainActivity) activity.getParent();
			mainActivity.switchTab(2);
			
//			Intent intent = new Intent(activity, ResultActivity.class);
//	        activity.startActivity(intent);
	      
			

		}
	}

}
